package com.fesine.ssh.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.fesine.ssh.model.Category;
import com.fesine.ssh.model.Menu;
import com.fesine.ssh.service.CategoryService;
import com.fesine.ssh.service.SequenceService;
import com.fesine.ssh.util.GenerateUUID;
import com.fesine.ssh.util.ResponseUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.List;

/**
 * Created by Fesine on 2016/2/21.
 */
@Controller
@RequestMapping("/sys")
public class SysController {

    private static final Logger logger = Logger.getLogger(SysController.class);

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SequenceService sequenceService;

    public static SerializeConfig mapping = new SerializeConfig();
    private String str = "";

    @RequestMapping("/loadRootMenuId")
    public void loadRootMenuId(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        Menu menu1 = new Menu("用户管理","test1.jsp",null,"",0,1);
        menu1.setId("111111");
        Menu menu2 = new Menu("栏目管理","test2.jsp",null,"",0,2);
        menu2.setId("222222");
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(menu1);
        jsonArray.add(menu2);

        ResponseUtil.write(resp, jsonArray.toString());
    }
    @RequestMapping("/loadNodeMenuId")
    public void loadNodeMenuId(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String pid = req.getParameter("pid");
        JSONArray jsonArray = new JSONArray();
        if (pid.equals("111111")){
            Menu menu1 = new Menu("用户管理","test1.jsp","111111","",1,1);
            menu1.setId("333333");
            Menu menu2 = new Menu("栏目管理","test2.jsp","111111","",1,2);
            menu2.setId("444444");
            jsonArray.add(menu1);
            jsonArray.add(menu2);
        }
        if (pid.equals("222222")){
            Menu menu1 = new Menu("用户管理","test1.jsp","222222","",1,1);
            menu1.setId("555555");
            Menu menu2 = new Menu("栏目管理","test2.jsp","222222","",1,2);
            menu2.setId("666666");
            jsonArray.add(menu1);
            jsonArray.add(menu2);
        }

        ResponseUtil.write(resp, jsonArray.toString());
    }

    @RequestMapping("/getUrlByMenuId")
    public void getUrlByMenuId(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String menuId = req.getParameter("menuId");
        String str = "";
        if (menuId.equals("333333")){
            Menu menu1 = new Menu("用户管理","test1.jsp","111111","",1,1);
            menu1.setId("333333");
            str = JSONObject.toJSONString(menu1);
        }
        if (menuId.equals("555555")){
            Menu menu1 = new Menu("用户管理","test1.jsp","222222","",1,1);
            menu1.setId("555555");
            str = JSONObject.toJSONString(menu1);
        }

        ResponseUtil.write(resp, str);
    }


    /**
     * 添加用户
     *
     * @param req
     * @param resp
     * @throws Exception
     */
    @RequestMapping("/addCategory")
    public void addUser(HttpServletRequest req, HttpServletResponse resp)
            throws Exception {
        Writer writer = resp.getWriter();
        StringBuffer sb = new StringBuffer();
        String text = req.getParameter("text");
        String description = req.getParameter("description");
        String parent = req.getParameter("parent");
        String leaf = req.getParameter("leaf");
        Category category = new Category();
        category.setId(GenerateUUID.getUUId());
        category.setCateId(sequenceService.genCateId());
        category.setText(text);
        category.setDescription(description);
        String id;
        if (null == parent || parent == "") {
            id = categoryService.addTopCategory(category);
        } else {
            id = categoryService.addChildCategory(Integer.parseInt(parent),category);
        }
        if (null != id) {
            sb.append("{success:true,msg:'类别添加成功!'}");
            logger.info("------->添加成功！");
        } else {
            sb.append("{success:true,msg:'类别添加失败!'}");
            logger.info("------->添加失败！");
        }
        writer.write(sb.toString());
    }

    @RequestMapping("/updateCategory")
    public void updateUser(HttpServletRequest req, HttpServletResponse resp, PrintWriter writer)
            throws Exception {
        String cateId = req.getParameter("cateId");
        String text = req.getParameter("text");
        String description = req.getParameter("description");
        Category category = categoryService.findByCateId(Integer.parseInt(cateId));
        category.setText(text);
        category.setDescription(description);
        try {
            categoryService.modify(category);
            writer.write("{success:true, msg:'类别修改成功!'}");
        } catch (Exception e) {
            writer.write("{success:true, msg:'类别修改失败!'}");
        }
    }

    @RequestMapping("/deleteCategory")
    public void deleteCategory(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String cateId = req.getParameter("cateId").replace("\"", "");
        //String[] IdsArr = cateIds.split(",");
        ////for (String s : IdsArr) {
        ////    logger.info("--------->"+ s);
        ////}
        StringBuffer sb = new StringBuffer();
        try {
            categoryService.deleteByCateId(Integer.parseInt(cateId));
            sb.append("{success:true,msg:'分类删除成功!'}");
            logger.info("------->删除分类成功！");
        } catch (Exception e) {
            logger.info("------->分类删除失败！");
            sb.append("{success:true,msg:'分类删除失败!'}");
            e.printStackTrace();
        }

        Writer writer = resp.getWriter();
        writer.write(sb.toString());

    }

    /**
     * 显示到combobox的列表的store
     *
     * @param request
     * @param writer
     */
    @RequestMapping(value = "/comboCategory", method = RequestMethod.GET)
    public void listCategoryToCombobox(HttpServletRequest request, PrintWriter writer) {
        List<Category> categories = categoryService.findAll();
        int len = categories.size();
        String preStr = "{totalCount:" + len + ",rows:[";
        String cenStr = "";
        int i = 0;
        String douhao = ",";
        for (Category c : categories) {
            i++;
            cenStr += "{cateId:'" + c.getCateId() + "', " +
                    "text:'" + c.getText() + "'" +
                    "}";
            if (i < len) {
                cenStr += douhao;
            }
        }
        String endStr = "]}";
        String resultStr = preStr + cenStr + endStr;
        writer.write(resultStr);
    }
}
